package com.liang.recommend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liang.recommend.algorithm.Latent_Factor;
import com.liang.recommend.mapper.UserActionMapper;
import com.liang.recommend.pojo.LatentFactor;
import com.liang.recommend.mapper.LatentFactorMapper;
import com.liang.recommend.pojo.Movie;
import com.liang.recommend.pojo.UserAction;
import com.liang.recommend.service.LatentFactorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.recommend.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小梁
 * @since 2020-12-25
 */
@Service
public class LatentFactorServiceImpl extends ServiceImpl<LatentFactorMapper, LatentFactor> implements LatentFactorService {

    @Autowired
    LatentFactorMapper latentFactorMapper;

    @Autowired
    MovieService movieService;
    @Autowired
    UserActionMapper userActionMapper;

    @Override
    public int toInsertLatentFactor(Double[][] matrixR,Long[] axisQ,Long[] axisP) {
        if (axisQ.length!=matrixR.length&&axisP.length!=matrixR[0].length){ //保证矩阵能相乘
            System.out.println("数据集有误无法插入");
        }else {
            LatentFactor latentFactor = new LatentFactor();
            latentFactor.setValue(0.0);
            int xTemp=0;
            int yTemp=0;
            QueryWrapper<UserAction> wrapper;
            Long[] movies;

            System.out.println("====================");
            System.out.println(matrixR.toString());

            for (Long x : axisQ) {
                latentFactor.setUserId(x);
                wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",x).orderByAsc("movie_id");
                List<UserAction> userActions = userActionMapper.selectList(wrapper);
                movies=new Long[userActions.size()];
                int mTemp=0;
                for (UserAction userAction : userActions) {
                    movies[mTemp]=userAction.getMovieId();
                    mTemp+=1;
                }
                for (Long y : axisP) {
                    yTemp=yTemp%axisP.length;//求模
                    if(yTemp>=movies.length){
                        latentFactor.setMovieId(y);
                        latentFactor.setValue(matrixR[xTemp][yTemp]);
                        latentFactorMapper.insert(latentFactor);
                    }else {
                        if (y != movies[yTemp]) {
                            latentFactor.setMovieId(y);
                            latentFactor.setValue(matrixR[xTemp][yTemp]);
                            latentFactorMapper.insert(latentFactor);
                        }
                    }
                    yTemp+=1;
                }
                xTemp+=1;
            }
        }
        return 0;
    }
}
